package com.product.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.alibaba.fastjson.JSONObject;
import com.product.system.config.GiteeUtils;
import com.product.system.domain.FactoryUser;
import com.product.system.service.FactoryUserService;
import com.product.system.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("factoryUser")
public class FactoryUserController {

    @Autowired
    FactoryUserService factoryUserService;

    @Autowired
    HttpServletResponse response;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;


    /**
     * 校验验证码+登录
     * @param factoryUser
     * @return
     */
    @RequestMapping("login")
    public Result login(@RequestBody FactoryUser factoryUser){
        //校验验证码
        String code = factoryUser.getCode();//获取用户输入的验证码
        String codeRedis= (String) redisTemplate.opsForValue().get(factoryUser.getUid());
        if(code==null){
            return Result.fail("请输入验证码");
        }

        if(!codeRedis.equals(code)){
            return Result.fail("验证码错误");
        }

        FactoryUser userDB= factoryUserService.selectGitName(factoryUser.getName());
        if(userDB==null){
         return Result.fail("用户名不存在");
        }

        if(!factoryUser.getPassword().equals(userDB.getPassword())){
            return Result.fail("密码错误");
        }

        String md5Hex = DigestUtil.md5Hex(JSONUtil.toJsonStr(userDB) + request.getRemoteAddr());
        if(!redisTemplate.opsForValue().setIfAbsent(md5Hex,"123",5,TimeUnit.MINUTES)){
            return Result.fail("请勿重复登录");
        }


        String token = JWT.create()
                .setPayload("user", userDB)
                .setSigner(JWTSignerUtil.none())
                .sign();
        return Result.success(token);
    }


    /**
     * 验证码
     */
    @RequestMapping("createImage")
    public void createImage(String uid) throws IOException {
        System.out.println("uid市:"+uid);
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uid,captcha.getCode(),2, TimeUnit.MINUTES);
    }



    @RequestMapping("callbackCode")
    public Result callbackCode(String code) throws IOException {
        System.out.println("获取到的临时授权码是:"+code);
        //获取token
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token是:"+tokenByCode);
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的用户资源是:"+userInfoByToken.toJSONString());
        //第三方用户名
        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        String name = userInfoByToken.getString("login");
        Integer giteeId = userInfoByToken.getInteger("id");

        //查询数据库以前登录过
        FactoryUser userDB= factoryUserService.selectGitName(name);
        if(userDB==null){
            FactoryUser factoryUser = new FactoryUser();
            factoryUser.setName(name);
            factoryUser.setAvatarUrl(avatarUrl);
            factoryUser.setNickName(nickName);
            factoryUser.setGiteeId(giteeId);
            factoryUserService.addFactoryUser(factoryUser);
        }else {//更新用户图片
            userDB.setAvatarUrl(avatarUrl);
            userDB.setNickName(nickName);
            factoryUserService.updateFactoryUser(userDB);
        }

        response.sendRedirect("http://localhost:8080/argpFactory");
        return Result.success();
    }

}
